package com.whf.security.browser;

import com.whf.security.browser.support.SimpleResponse;
import com.whf.security.core.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 该类负责验证跳转过来的网址是否为html结尾的url
 * 是的话就进入登陆页面,不是的话就进入提示登陆页面
 */
@RestController
@Slf4j
public class BrowserSecurityController {
    //该对象中在跳转前会将url存放在该对象中
    private RequestCache requestCache = new HttpSessionRequestCache();
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;
    //当身份认证时跳转到这里
    @RequestMapping("/authentication/require")
    //当有返回值时返回状态码(401未授权)
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public SimpleResponse requireAuthentication(HttpServletRequest request,
                                        HttpServletResponse response) throws IOException {

        //获得跳转源
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if(savedRequest!=null){
            String target = savedRequest.getRedirectUrl();
            log.info("[登陆跳转controller] 引发跳转的url:{}",target);
            if(StringUtils.endsWithIgnoreCase(target,".html")){
                //由html结尾的url引发的跳转,所以直接跳转到登陆页面,第三个参数是登陆页面的url
                redirectStrategy.sendRedirect(request,response,securityProperties.getBrowser().getLoginPage());
            }
        }

        return new SimpleResponse("访问的服务需要身份认证");

    }


}
